package com.hnas.eCard.dao.impl;

import java.util.Date;
import java.util.List;

import javax.persistence.Query;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import com.hnas.core.dao.BaseDaoImpl;
import com.hnas.core.util.DateUtil;
import com.hnas.core.util.StringUtil;
import com.hnas.eCard.dao.CommoditMrchDao;
import com.hnas.eCard.orm.CommoditMrch;

@Component("commoditMrchDao")
public class CommoditMrchDaoImpl extends BaseDaoImpl<CommoditMrch> implements CommoditMrchDao{

	public CommoditMrchDaoImpl() {
		super(CommoditMrch.class);
	}

	@Override
	public CommoditMrch saveOrUpdate(CommoditMrch vo) throws Exception {
		CommoditMrch temp = null;
		if(null != vo){
			if(StringUtil.isNotEmpty(vo.getId())){
				temp = this.find(vo.getId());
			}
			if(null == temp){
				temp = vo;
				temp.setCreateTime(DateUtil.dateTimeToString(new Date()));
				temp.setUpdateTime(DateUtil.dateTimeToString(new Date()));
				temp.setIsDeleted(false);
				this.persist(temp);
			}else{
				BeanUtils.copyProperties(vo, temp,new String[]{"id", "createTime"});
				temp.setUpdateTime(DateUtil.dateTimeToString(new Date()));
				this.merge(temp);
			}
		}
		return temp;
	}

	@Override
	public List<CommoditMrch> listCommoditMrch() {
		String sql = "select * from tbl_commodit_mrch";
		Query query = this.entityManager.createNativeQuery(sql, CommoditMrch.class);
		return query.getResultList();
	}

	@Override
	public String findMrch(String orderNo) {
		String sql = "select distinct(t2.mrch_id) from tbl_commodit_detail_re t1 left join tbl_commodit t2 on t1.commodit_id = t2.id where t1.order_no = ?1";
		Query query = this.entityManager.createNativeQuery(sql);
		query.setParameter(1, orderNo);
		List<String> resultList = query.getResultList();
		if(resultList != null && resultList.size() > 0) {
			StringBuffer sb = new StringBuffer();
			for(String re : resultList) {
				sb.append(re).append(",");
			}
			return sb.substring(0, sb.length()-1);
		}
		return null;
	}

}
